define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'mall/goods/goods/index',
                    add_url: 'mall/goods/goods/add',
                    edit_url: 'mall/goods/goods/edit',
                    del_url: 'mall/goods/goods/del',
                    multi_url: 'mall/goods/goods/multi',
                    detail_url: '/addons/mall/goods/detail',
                    table: 'mall_goods_goods',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('ID')},
                        {field: 'shop_id', title: __('Shop_id')},
                        {field: 'goodssn', title: __('Goodssn'), visible:false},
                        {field: 'productno', title: __('Productno'), visible:false},
                        {field: 'goodsname', title: __('Goodsname'), align:'left'},
                        {field: 'goodsimg', title: __('Goodsimg'), formatter: Table.api.formatter.image},
                        {field: 'marketprice', title: __('Marketprice'), operate:'BETWEEN', visible:false},
                        {field: 'shopprice', title: __('Shopprice'), operate:'BETWEEN', visible:false},
                        {field: 'warnstock', title: __('Warnstock'), visible:false},
                        {field: 'goodsstock', title: __('Goodsstock'), visible:false},
                        {field: 'goodsunit', title: __('Goodsunit'), visible:false},
                        {field: 'goodsstatus', title: __('Goodsstatus'), searchList: {"1":__('Yes'),"0":__('No')}, formatter: Table.api.formatter.toggle},
                        {field: 'bestis', title: __('Bestis'), searchList: {"1":__('Yes'),"0":__('No')}, formatter: Table.api.formatter.toggle},
                        {field: 'hotis', title: __('Hotis'), searchList: {"1":__('Yes'),"0":__('No')}, formatter: Table.api.formatter.toggle},
                        {field: 'newis', title: __('Newis'), searchList: {"1":__('Yes'),"0":__('No')}, formatter: Table.api.formatter.toggle},
                        {field: 'recomis', title: __('Recomis'), searchList: {"1":__('Yes'),"0":__('No')}, formatter: Table.api.formatter.toggle},
                        {field: 'goodscat_ids', title: __('Goodscat_ids'), visible:false},
                        {field: 'shopcat_ids', title: __('Shopcat_ids'), visible:false},
                        {field: 'brand_id', title: __('Brand_id'), visible:false},
                        {field: 'salenum', title: __('Salenum'), visible:false},
                        {field: 'saletime', title: __('Saletime'), operate:'RANGE', addclass:'datetimerange', visible:false},
                        {field: 'visitnum', title: __('Visitnum'), visible:false},
                        {field: 'appraisenum', title: __('Appraisenum'), visible:false},
                        {field: 'specis', title: __('Specis'), searchList: {"1":__('Yes'),"0":__('No')}, formatter: Table.api.formatter.toggle, visible:false},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime, visible:false},
                        {field: 'goodstype', title: __('Goodstype'), searchList: {"0":__('Goodstype 0'),"1":__('Goodstype 1')}, formatter: Table.api.formatter.normal, visible:false},
                        {field: 'freighttype', title: __('Freeshippingis'), searchList: {"1":__('Yes'),"0":__('No')}, formatter: Table.api.formatter.toggle, visible:false},
                        {field: 'weight', title: __('weight'), visible:false},
                        {field: 'status', title: __('Status'), searchList: {"sale":__('Status sale'),"audit":__('Status audit'),"store":__('Status store'),"illegal":__('Status illegal'),"warn":__('Status warn')}, formatter: Table.api.formatter.status, visible:false},
                        {field: 'datalist', title: __('Operate'), table: table,
                            buttons: [
                                {
                                    name: 'goodsspecitem',
                                    text: '规格项',
                                    classname: 'btn btn-xs btn-success btn-addtabs',
                                    icon: 'fa fa-th-list',
                                    url: 'mall/goods/specitem?goods_id={ids}&cat_ids={goodscat_ids}'
                                },
                                {
                                    name: 'goodsspec',
                                    text: '销售规格',
                                    classname: 'btn btn-xs btn-success btn-addtabs',
                                    icon: 'fa fa-list-ul',
                                    url: 'mall/goods/salespec?goods_id={ids}&cat_ids={goodscat_ids}'
                                },
                                {
                                    name: 'goodsattr',
                                    text: '属性',
                                    classname: 'btn btn-xs btn-info btn-fields btn-dialog',
                                    icon: 'fa fa-list',
                                    url: 'mall/goods/goodsattr?goods_id={ids}&cat_ids={goodscat_ids}'
                                },
                                {
                                    name: 'getTBGoods',
                                    text: '导入',
                                    classname: 'btn btn-xs btn-info btn-fields btn-dialog',
                                    icon: 'fa fa-text-o',
                                    url: 'mall/goods/goods/gettbgoods'
                                },
                            ],
                            formatter: Table.api.formatter.buttons
                        },
                        {field: 'operate', title: __('Operate'), table: table,
                            events: Table.api.events.operate,
                            buttons: [{
                                name: 'detail',
                                title: __('Detail'),
                                icon: 'fa fa-eye',
                                classname: 'btn btn-info btn-xs btn-detail',
                                extend: "target='_blank'",
                                url: '/addons/mall/goods/detail'
                            }],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
            $("input[name='row[goodstype]']:first").trigger("click");
            $("input[name='row[freighttype]']:last").trigger("click");
        },
        edit: function () {
            Controller.api.bindevent();
            $("input[name='row[goodstype]']:checked").trigger("fa.event.goodstypeupdated", "edit");
            $("input[name='row[freighttype]']:checked").trigger("fa.event.freighttypeupdated", "edit");
            $("input[name='row[status]']:checked").trigger("fa.event.statusupdated", "edit");
            $("#c-category1").trigger("fa.event.category1updated",'edit');
            $("#c-shopcat1").trigger("fa.event.shopcat1updated",'edit');
        },
        gettbgoods: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                //不可见的元素不验证
                $("form[role=form]").data("validator-options", {ignore: ':hidden'});
                $(document).on("click fa.event.goodstypeupdated", "input[name='row[goodstype]']", function (e, ref) {
                    $(".gtf").addClass("hidden");
                    $(".gtf.gtf-" + $(this).val()).removeClass("hidden");
                });
                $(document).on("click fa.event.freighttypeupdated", "input[name='row[freighttype]']", function (e, ref) {
                    $(".tf").addClass("hidden");
                    $(".tf.tf-" + $(this).val()).removeClass("hidden");
                });
                $(document).on("click fa.event.statusupdated", "input[name='row[status]']", function (e, ref) {
                    $(".stf").addClass("hidden");
                    $(".stf.stf-" + $(this).val()).removeClass("hidden");
                });
                Form.api.bindevent($("form[role=form]"));
                $("#c-category2").data("params", function (obj) {
                    return {custom: {pid: $("#c-category1").val()}};
                });
                $("#c-category3").data("params", function (obj) {
                    return {custom: {pid: $("#c-category2").val()}};
                });
                $("#c-shopcat2").data("params", function (obj) {
                    return {custom: {pid: $("#c-shopcat1").val()}};
                });
                $("#c-brandId").data("params", function (obj) {
                    return {custom: {cat_id: $("c-category1").val()}};
                });
                //一级分类选定，初始化品牌选择器，清除二、三级选项
                $(document).on("change", "#c-category1", function () {
                    $.post("mall/goods/brands/selectpage",{custom: {cat_id: $(this).val()},},function(result){
                        var i = $('#c-brand_id').val();
                        $('#c-brand_id').selectPageData(result.list);
                        $('#c-brand_id').val(i);
                        $('#c-brand_id').selectPageRefresh();
                    });
                    require(['selectpage'], function () {
                        $('#c-category2').selectPageClear();
                        $('#c-category3').selectPageClear();
                    });
                });
                //二级分类选定，清除三级选项
                $(document).on("change", "#c-category2", function () {
                    require(['selectpage'], function () {
                        $('#c-category3').selectPageClear();
                    });
                });
                //一级店铺分类选定，清除二级选项
                $(document).on("change", "#c-shopcat1", function () {
                    require(['selectpage'], function () {
                        $('#c-shopcat2').selectPageClear();
                    });
                });
                //三级分类选定，初始化规格属性页面
                $(document).on("change", "#c-category3", function () {
                    if($(this).val()){
                        Controller.events.getSpecAttrs($(this).val());
                    }else{
                        $('.layer-footer').hide();
                        $('#specsAttrBox').empty();
                    }
                });
                //拼接三级分类选项值，用于保存
                $(document).on("change", "#c-category3", function () {
                    $("#c-goodscat_ids").val( $("#c-category1").val()+","+$("#c-category2").val()+","+$(this).val());
                });
                //三级分类默认值设置（只执行一次）
                $(document).one("fa.event.category1updated", "#c-category1", function () {
                    var a = $("#c-goodscat_ids").val().split(",");
                    $("#c-category1").val(a[0]);
                    $("#c-category2").val(a[1]);
                    $("#c-category3").val(a[2]);
                });
                //拼接两级店铺分类选项值，用于保存
                $(document).on("change", "#c-shopcat2", function () {
                    $("#c-shopcat_ids").val( $("#c-shopcat1").val()+","+$(this).val());
                });
                //两级店铺分类默认值设置（只执行一次）
                $(document).one("fa.event.shopcat1updated", "#c-shopcat1", function () {
                    var a = $("#c-shopcat_ids").val().split(",");
                    $("#c-shopcat1").val(a[0]);
                    $("#c-shopcat2").val(a[1]);
                });
            }
        }
    };
    return Controller;
});